//
//  LoginMethodViewController.swift
//  ezyform
//
//  Created by Moennig Q on 13/7/2022.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import MBProgressHUD
import LocalAuthentication
enum LoginMethodOperation: String {
    case gesture = "gesture"
    case touchID = "touchid"
    case faceID = "faceid"
    case password = "password"
    case gestureSetting = "gestureSetting"
    case loginMethodGuide = "loginMethodGuide"
}
class LoginMethodSettingViewController: ModelBaseViewController {
    var isGuideFlag: Bool = false//是否是引导图
    var customView = LoginMethodView()
    var list = [LoginMethodModel]()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.customView.toGestureSettingClosure = {[weak self] in
            guard let strongSelf = self else { return }
            strongSelf.toGestureSetting()
        }
        self.customView.settingClosure = {[weak self] (model, isOn) in
            guard let strongSelf = self else { return }
            if model.operType == .faceID || model.operType == .touchID{//face id , touch id
                let biometryTypeName = LoginMethodServcie().getBiometryTypeName(model.operType)
                if isOn {//开启后
                    let (usefullType, errType) = LoginMethodServcie().getUsefulBiometryType()
                    if let code = errType {//返回错误
                        switch code {
                        case LAError.Code.biometryNotEnrolled://没有录入指纹或face id
                            let errMessage = "You haven't set a \(biometryTypeName). Please go to Settings > \(biometryTypeName) and Passcode and enter a \(biometryTypeName)"
                            Tool().showAlertViewWithOneBtn(message: errMessage) {
                                strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                            }
                        case LAError.Code.biometryLockout://连续五次指纹识别错误，TouchID功能被锁定，下一次需要输入系统密码
                            LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Too many attempts, please input your password") { success, _ in
                                print(Thread.current)
                                DispatchQueue.main.async {
                                    print(Thread.current)
                                    if success {
                                        strongSelf.refreshDataAfterSetting(model.operType, isOn: true)
                                    }else{
                                        strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                                    }
                                }
                            }
                        case LAError.Code.passcodeNotSet://此设备未设置系统密码
                            let errMessage = "You have't set up an unlock password in your phone, please go to \"Setting > \(biometryTypeName) and Password\""
                            
                            Tool().showAlertViewWithOneBtn(message: errMessage) {
                                strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                            }
                            
                        default:
                            //"No permission to access '\(biometryTypeName)'. please turn it on"
                            Tool().showAlertViewWithTwoBtns(title: biometryTypeName + " have to be enabled when using the app",message: "Turn on \(biometryTypeName) to verify identity", cancelStr: "Cancel", confirmStr: "Settings") {
                                strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                            } yesClosure: {
                                //face id不可用，开启不成功
                                strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                                guard let url = URL(string: UIApplication.openSettingsURLString) else {
                                    return
                                }
                                if UIApplication.shared.canOpenURL(url){
                                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                                }
                            }
                            break
                        }
                    }else {
                        if usefullType == .faceID {//提示成功
                            LoginMethodServcie().setLoginMethodFlag(model.operType, isOn: true)
                            MBProgressHUD.showToast(parentView: strongSelf.customView, text: "Face Recognition set successfully")
                        }else if usefullType == .touchID {//提示成功
                            LoginMethodServcie().setLoginMethodFlag(model.operType, isOn: true)
                            MBProgressHUD.showToast(parentView: strongSelf.customView, text: "Touch Recognition set successfully")
                        }
                    }
                }else{
                    LoginMethodServcie().setLoginMethodFlag(model.operType, isOn: false)
                }
                strongSelf.dealAfterSettingForGuide()
            }else{//gesture
                if isOn {//开启后,自动设置手势
                    strongSelf.toGestureSetting()
                }else{
                    strongSelf.refreshDataAfterSetting(model.operType, isOn: false)
                    strongSelf.dealAfterSettingForGuide()
                }
            }
        }
        self.initUI()
        self.initData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshLoginMethodSetting), name: NSNotification.Name(rawValue: "me.loginmethod.setting"), object: nil)
    }
    private func refreshDataAfterSetting(_ operType: LoginMethodOperation, isOn: Bool, gesturePwd: String = ""){
        LoginMethodServcie().setLoginMethodFlag(operType, isOn: isOn,result: gesturePwd)
        self.initData()
    }
    private func initUI(){
        self.view = self.customView
        
        if self.isGuideFlag {//引导功能的标题，提示
            self.customView.setTitle(R.string.localizable.setMoreLoginMethods())
            self.customView.settingTipLabel.isHidden = false
            self.customView.backToPreBtn.isHidden = true
            self.setRightBarItem(R.string.localizable.skip())
            self.customView.closeBtn.addTarget(self, action: #selector(closeGuideVC), for: UIControl.Event.touchUpInside)
        }else{
            self.customView.setTitle(R.string.localizable.loginMethod())
            self.customView.settingTipLabel.isHidden = true
            self.customView.closeBtn.addTarget(self, action: #selector(dismissVC), for: UIControl.Event.touchUpInside)
        }
        
    }
    //MARK: - 关闭login method 引导图
    @objc private func closeGuideVC(){
        LoginMethodServcie().initRootVC()
    }
    private func initData(){
        //
        self.list.removeAll()
        //gesture
        var gestureModel = LoginMethodModel()
        gestureModel.operType = .gesture
        gestureModel.isOn = LoginMethodServcie().getLoginMethodFlag(.gesture)
        list.append(gestureModel)
        //开启了gesture要显示setting
        if gestureModel.isOn {
            var gestureSetting = LoginMethodModel()
            gestureSetting.operType = .gestureSetting
            list.append(gestureSetting)
        }
        
        let type = LoginMethodServcie().getSupportedBiometryType()
        //当前设备支持的是touch id
        if type == .touchID {
            var touchModel = LoginMethodModel()
            touchModel.operType = .touchID
            touchModel.isOn = LoginMethodServcie().getLoginMethodFlag(.touchID)
            //如果touchid 不可用，要直接关闭
            let (usefullType, _) = LoginMethodServcie().getUsefulBiometryType()
            if usefullType != .touchID {
                LoginMethodServcie().setLoginMethodFlag(.touchID, isOn: false)
                touchModel.isOn = false
            }
            list.append(touchModel)
        }else{
            LoginMethodServcie().setLoginMethodFlag(.touchID, isOn: false)
        }
        //当前设备支持的是face id
        if type == .faceID {
            var faceModel = LoginMethodModel()
            faceModel.operType = .faceID
            faceModel.isOn = LoginMethodServcie().getLoginMethodFlag(.faceID)
            //如果face id 不可用，要直接关闭
            let (usefullType, _) = LoginMethodServcie().getUsefulBiometryType()
            if usefullType != .faceID {//如果touchid 不可用，要直接关闭
                LoginMethodServcie().setLoginMethodFlag(.faceID, isOn: false)
                faceModel.isOn = false
            }
            list.append(faceModel)
        }else{
            LoginMethodServcie().setLoginMethodFlag(.faceID, isOn: false)
        }
        self.customView.list = list
        self.customView.tableView.reloadData()
    }
    @objc
    func refreshLoginMethodSetting(){
        self.initData()
    }
    private func dealAfterSettingForGuide(){
        if self.isGuideFlag {//引导图才有此效果
            let totalCnt = self.list.filter({$0.operType != .gestureSetting}).count
            var opentCnt: Int = 0
            for loginModel in self.list{
                if LoginMethodServcie().getLoginMethodFlag(loginModel.operType){
                    opentCnt += 1
                }
            }
            if opentCnt == 0{//没有设置显示skip
                self.setRightBarItem(R.string.localizable.skip())
            }else{
                if totalCnt == opentCnt {
                    let delay = Double(1.2) * Double(NSEC_PER_SEC)
                    let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)
                    DispatchQueue.main.asyncAfter(deadline: time) {//设置完成，要等成功提示语显示完再跳转到主界面，延时1秒钟和toast一样
                        LoginMethodServcie().initRootVC()
                    }
                }else if totalCnt > opentCnt {
                    self.setRightBarItem(R.string.localizable.done())
                }
            }
        }
    }
    //MARK: - skip按钮，ti
    private func setRightBarItem(_ title: String){
        self.customView.closeBtn.setImage(nil, for: UIControl.State.normal)
        self.customView.closeBtn.setTitle(title, for: UIControl.State.normal)
        self.customView.closeBtn.setTitleColor(UIColor(hexStr: "#379657"), for: UIControl.State.normal)
        self.customView.closeBtn.setFont(R.font.interMedium(size: 15))
        self.customView.closeBtn.addTarget(self, action: #selector(skipBtnClick), for: UIControl.Event.touchUpInside)
    }
    func toGestureSetting(){
        let vc = GestureSettingViewController()
        vc.isGuideFlag = self.isGuideFlag
        vc.settingClosure = { [weak self] (gesturePwd) in
            guard let strongSelf = self else { return }
            if gesturePwd == ""{//没有设置密码直接返回上一级
                let setFlag = LoginMethodServcie().getLoginMethodFlag(.gesture)
                if setFlag == false {//手势没有设置过密码，返回空依旧不设置密码
                    strongSelf.refreshDataAfterSetting(.gesture, isOn: false, gesturePwd: gesturePwd)
                }
            }else{//设置密码成功
                strongSelf.refreshDataAfterSetting(.gesture, isOn: true, gesturePwd: gesturePwd)
                //show success toast
                MBProgressHUD.showToast(parentView: strongSelf.customView, text: R.string.localizable.gestureLoginSetSuccessfully())
                strongSelf.dealAfterSettingForGuide()
            }
        }
        self.navigationController?.pushViewController(vc, animated: false)
    }
    
    @objc
    func skipBtnClick(){
        LoginMethodServcie().initRootVC()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        DebugLog("\(self) didReceiveMemoryWarning")
    }
}
